import { Injectable, ConflictException, NotFoundException, BadRequestException, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Share } from './share.entity';
import { NovelService } from '../novel/novel.service';
import { CrawlerService } from '../crawler/crawler.service';

@Injectable()
export class ShareService {
  private readonly logger = new Logger(ShareService.name);

  constructor(
    @InjectRepository(Share)
    private shareRepository: Repository<Share>,
    private novelService: NovelService,
    private crawlerService: CrawlerService,
  ) {}

  async createShare(userId: number, novelId: number, shareMessage?: string): Promise<Share> {
    // 检查小说是否存在
    try {
      await this.novelService.findOne(novelId);
    } catch (error) {
      throw new NotFoundException('小说不存在');
    }

    // 检查是否已经分享过
    const existingShare = await this.shareRepository.findOne({
      where: { userId, novelId },
    });

    if (existingShare) {
      throw new ConflictException('您已经分享过这本小说');
    }

    const share = this.shareRepository.create({
      userId,
      novelId,
      shareMessage,
      isPublic: true,
    });

    const savedShare = await this.shareRepository.save(share);

    // 更新小说分享次数
    await this.novelService.updateShareCount(novelId);

    return savedShare;
  }

  async getUserShares(userId: number, page = 1, limit = 10): Promise<{ shares: Share[]; total: number }> {
    const [shares, total] = await this.shareRepository.findAndCount({
      where: { userId, isPublic: true },
      relations: ['novel'],
      order: { sharedAt: 'DESC' },
      take: limit,
      skip: (page - 1) * limit,
    });

    return { shares, total };
  }

  async getNovelShares(novelId: number, page = 1, limit = 10): Promise<{ shares: Share[]; total: number }> {
    const [shares, total] = await this.shareRepository.findAndCount({
      where: { novelId, isPublic: true },
      relations: ['user'],
      order: { sharedAt: 'DESC' },
      take: limit,
      skip: (page - 1) * limit,
    });

    return { shares, total };
  }

  async getPublicShares(page = 1, limit = 10): Promise<{ shares: Share[]; total: number }> {
    const [shares, total] = await this.shareRepository.findAndCount({
      where: { isPublic: true },
      relations: ['user', 'novel'],
      order: { sharedAt: 'DESC' },
      take: limit,
      skip: (page - 1) * limit,
    });

    return { shares, total };
  }

  async updateShareViewCount(shareId: number): Promise<void> {
    await this.shareRepository.increment({ id: shareId }, 'viewCount', 1);
  }

  async deleteShare(userId: number, shareId: number): Promise<void> {
    const share = await this.shareRepository.findOne({
      where: { id: shareId, userId },
    });

    if (!share) {
      throw new NotFoundException('分享记录不存在');
    }

    await this.shareRepository.remove(share);
  }

  /**
   * 从分享链接创建分享
   */
  async createShareFromLink(userId: number, shareUrl: string, shareMessage?: string) {
    this.logger.log(`开始处理链接分享: ${shareUrl}`);

    try {
      // 使用爬虫服务解析链接并获取小说信息
      const novel = await this.crawlerService.crawlNovelFromUrl(shareUrl);

      this.logger.log(`链接解析成功，小说: ${novel.title}`);

      // 检查是否已经分享过这本小说
      const existingShare = await this.shareRepository.findOne({
        where: { userId, novelId: novel.id },
      });

      if (existingShare) {
        throw new ConflictException('您已经分享过这本小说了');
      }

      // 创建分享记录
      const share = this.shareRepository.create({
        userId,
        novelId: novel.id,
        shareMessage,
        viewCount: 0,
      });

      const savedShare = await this.shareRepository.save(share);
      this.logger.log(`分享记录创建成功: ${savedShare.id}`);

      // 返回分享结果
      return {
        shareId: savedShare.id,
        novelId: novel.id,
        novelInfo: {
          id: novel.id,
          title: novel.title,
          author: novel.author,
          cover: novel.cover,
          description: novel.description,
          category: novel.category,
        },
      };
    } catch (error) {
      this.logger.error(`链接分享处理失败: ${error.message}`, error.stack);

      if (error instanceof ConflictException || error instanceof NotFoundException) {
        throw error;
      }

      throw new BadRequestException(`链接解析失败: ${error.message}`);
    }
  }
}